package com.alamiya.security.service.impl;

import com.alamiya.security.entity.PublicUser;
import com.alamiya.security.mapper.PublicUserMapper;
import com.alamiya.security.service.IPublicAuthorityService;
import com.alamiya.security.service.IPublicRoleService;
import com.alamiya.security.service.IPublicUserRoleRelationService;
import com.alamiya.security.service.IPublicUserService;
import com.alamiya.security.util.SecurityUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Optional;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author hehaoqi
 * @since 2021-02-02
 */
@Slf4j
@Service
public class PublicUserServiceImpl extends ServiceImpl<PublicUserMapper, PublicUser> implements IPublicUserService {

    @Autowired
    IPublicUserRoleRelationService userRoleRelationService;

    @Autowired
    IPublicRoleService roleService;

    @Autowired
    IPublicAuthorityService authorityService;

    @Override
    public Optional<PublicUser> getOneWithRolesAndAuthorities(String loginInfo) {
        LambdaQueryWrapper<PublicUser> lqw = new LambdaQueryWrapper<>();
        lqw.eq(PublicUser::getUsername, loginInfo);
        PublicUser user = getOne(lqw);
        if (Objects.isNull(user)) {
            log.warn("用户'{}'不存在", loginInfo);
        }
        complete(user);
        return Optional.ofNullable(user);
    }

    @Override
    public Optional<PublicUser> getUserWithAuthorities() {
        return SecurityUtils.getCurrentUsername().flatMap(username -> getOneWithRolesAndAuthorities(username));
    }

    private PublicUser complete(PublicUser user) {
        if (Objects.isNull(user)) {
            return user;
        }
        List<String> roleIds = userRoleRelationService.listRoleIdsByUserId(user.getId());
        List<String> roleNames = new ArrayList<>(roleIds.size());
        List<String> authorityNames = new ArrayList<>();
        for (String roleId : roleIds) {
            String roleName = roleService.getRoleName(roleId);
            if (StringUtils.isNotBlank(roleName)) {
                roleNames.add(roleName);
            }
        }
        user.setRoleNames(roleNames);
        return user;
    }
}
